package com.ldl.origami.controller.system;

import com.ldl.origami.domain.User;
import com.ldl.origami.origamiService.LoginService;
import com.ldl.origami.util.Constants;
import com.ldl.origami.util.InitServlet;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 功能描述:
 * 作者: LDL
 * 创建时间: 2014/7/15 14:47
 */
@Controller
public class LoginController {

    static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired(required = false)
    private LoginService loginService;

    @RequestMapping(value = "/loginIndex")
    public ModelAndView loginIndex(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("email", "");
        modelAndView.setViewName("login");
        return modelAndView;
    }



    /**
     * 验证登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/checkLogin")
    @ResponseBody
    public String checkLogin(HttpServletRequest request,HttpServletResponse response) {
        String result = "";
        String email = request.getParameter("email");
        String passwd = request.getParameter("passwd");
        String checked = request.getParameter("checked");
        List<User> users = loginService.checkLogin(email, DigestUtils.md5Hex(passwd));
        if(users == null){
            result = "error";
        }else if(users.size()==0){
            result = "fail";
        }else{
            result = "succ";
            HttpSession session = request.getSession();
            //session.setAttribute(Constants.SESSION_USER,users.get(0));
            session.setAttribute(Constants.SESSION_USERNAME,users.get(0).getUserName());
            //选择记住我
            if(checked.equals("1")){
                Cookie cookie = new Cookie("userName",users.get(0).getUserName());
                cookie.setMaxAge(InitServlet.cookieTime);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return result;
    }
}
